//
// Created by 123 on 2024/3/7.
//计算中缀表达式


#include <iostream>
#include "../0.utils/Char_Stack.cpp"


//获得操作符的优先级号
int getOpeNum(char a);

//是否是数字
bool isOpe(char ch);

//计算
int calculate(int a, int b, char ch);

//中缀表达式的计算
int computer(string str);


int main() {


    string s = "((5/(7-(1+1)))*3)-(2+(1+1))";
    string str = "5711+-/3*211++-";
    cout << "结果为： " << computer(s) << endl;

}

int computer(string str) {
    LinkStack numStack = init_CharStack();
    LinkStack opeStack = init_CharStack();
    for (int i = 0; i < str.length(); ++i) {
        char ch = str[i];
        if (isOpe(ch)) {
            if (ch == '(') {
                push(opeStack, ch);
                continue;
            }
            if (ch == ')') {
                char c = pop(opeStack);
                while (c != '(') {

                    int b = pop(numStack);
                    int a = pop(numStack);
                    int n = calculate(a, b, c);
                    push(numStack, n);

                    c = pop(opeStack);
                }
                continue;
            }
            if (!isEmpty(opeStack)) {
                char ch_ope = getTop(opeStack);
                while (getOpeNum(ch) <= getOpeNum(ch_ope)) {
                    if (getTop(opeStack) == '(')
                        break;

                    ch_ope = pop(opeStack);
                    int b = pop(numStack);
                    int a = pop(numStack);
                    int n = calculate(a, b, ch_ope);
                    push(numStack, n);

                    if (isEmpty(opeStack))
                        break;
                }
            }
            push(opeStack, ch);
        } else {
            push(numStack, ch - 48);
        }
    }
    while (!isEmpty(opeStack)) {
        char c = pop(opeStack);
        int b = pop(numStack);
        int a = pop(numStack);
        int n = calculate(a, b, c);
        push(numStack, n);
    }
    return pop(numStack);
}


bool isOpe(char ch) {
    return ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '(' || ch == ')';
}

int calculate(int a, int b, char ch) {
    if (ch == '+') {
        return a + b;
    } else if (ch == '-') {
        return a - b;
    } else if (ch == '*') {
        return a * b;
    } else {
        return a / b;
    }
}

int getOpeNum(char a) {
    if (a == '*' || a == '/')
        return 1;
    else if (a == '(')
        return 0;
    else
        return -1;
}

